package auth.config;

import auth.realm.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

//配置类
@Configuration
public class MyConfig{

	//shiro配置
	@Bean
	public ShiroFilterFactoryBean shiroFilterFactoryBean(
			DefaultWebSecurityManager defaultWebSecurityManager) {
		ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
		shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
		//设置拦截信息
		Map<String, String> filterMap=new HashMap<String, String>();
		filterMap.put("/**", "anon");//全部放行
		/*filterMap.put("/js/**", "anon");//静态资源
		filterMap.put("/fonts/**", "anon");//静态资源
		filterMap.put("/img/**", "anon");//静态资源
		filterMap.put("/login", "anon");//登录页面
		filterMap.put("/loginsubmit", "anon");//登录提交*/
		filterMap.put("/logout", "logout");//退出
		/*filterMap.put("/**", "authc");*/

		/*shiroFilterFactoryBean.setLoginUrl("/login");*///拦截跳转登录页面
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
		return shiroFilterFactoryBean;
	}
	@Bean//安全管理器
	public DefaultWebSecurityManager defaultWebSecurityManager(MyRealm myRealm) {
		DefaultWebSecurityManager defaultWebSecurityManager=new DefaultWebSecurityManager();
		defaultWebSecurityManager.setRealm(myRealm);
		return defaultWebSecurityManager;
	}
	@Bean//自己的realm
	public MyRealm myRealm(CacheManager cacheManagerSh,HashedCredentialsMatcher credentialsMatcher) {
		MyRealm myRealm=new MyRealm();
		myRealm.setCacheManager(cacheManagerSh);
		myRealm.setCredentialsMatcher(credentialsMatcher);
		return myRealm;
	}
	@Bean//缓存
	public MemoryConstrainedCacheManager cacheManagerSh() {
		return new MemoryConstrainedCacheManager();
	}
	@Bean//凭证匹配器
	public HashedCredentialsMatcher credentialsMatcher() {
		HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
		credentialsMatcher.setHashIterations(2);
		credentialsMatcher.setHashAlgorithmName("MD5");
		return credentialsMatcher;
	}
	/*@Bean//权限标签
	public ShiroDialect shiroDialect() {
		return new ShiroDialect();
	}*/
}
